// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use tauri::command;
use tracing::{info, Level};
use crate::youdao::models::{Dict};

use chrono::prelude::*;
// use tauri_plugin_log::{LogLevel, };

// #[derive(Debug, Deserialize)]
// pub struct RequestBody {
//   id: i32,
//   name: String,
// }

pub struct Database;

// the payload type must implement `Serialize` and `Clone`.
#[derive(Clone, serde::Serialize)]
pub struct Payload {
  pub message: String,
}

#[derive(serde::Serialize)]
pub struct CustomResponse {
  message: String,
  other_val: usize,
}

use std::{thread, time};

async fn some_other_function() -> Option<String> {
  let millis = time::Duration::from_millis(2000);

  thread::sleep(millis);

  let dt = Local::now();
  Some(format!(
    "{}@{}",
    "response",
    dt.format("%Y-%m-%d %H:%M:%S").to_string()
  ))
}

#[tauri::command]
pub async fn my_custom_command(
  window: tauri::Window,
  number: usize,
  database: tauri::State<'_, Database>,
) -> Result<CustomResponse, String> {
  println!("Called from window:{}", window.label());

  let dt = Local::now();

  window
    .emit(
      "rust-event",
      Some(Payload {
        message: format!(
          "{}@{}",
          "my_custom_command From Backend Rust Event: my_custom_command is awesome!",
          dt.format("%Y-%m-%d %H:%M:%S").to_string()
        ),
      }),
    )
    .expect("failed to emit");

  let result: Option<String> = some_other_function().await;
  if let Some(message) = result {
    Ok(CustomResponse {
      message,
      other_val: 42 + number,
    })
  } else {
    Err("No result".into())
  }
}

// #[command]
// pub fn perform_request(endpoint: String, body: RequestBody) -> String {
//   info!("{} {:?}", endpoint, body);
//   "message response".into()
// }

#[command]
pub async fn greet(name: String, age: u8) -> String {
  // tauri_plugin_log::logyyy(
  //   LogLevel::Debug,
  //   format!("start calling greet name={}", name),
  // );

  //tauri_plugin_sqlite::character_create().await;

  // tauri_plugin_log::logzzz(
  //   LogLevel::Debug,
  //   format!("start calling greet name={}", name),
  // );

  //tauri_plugin_sqlite::character_count().await;

  // let gres :Option<String>= graphql::gsample().await;

  // tauri_plugin_log::logzzz(
  //   LogLevel::Debug,
  //   format!("gsample gres={:?}", gres),
  // );

  let port = 2323;
  let dt = Local::now();

  // implicit return, because no semicolon!
  format!(
    "Hello {}, {} year-old human! @{}, port={}",
    name,
    age,
    dt.format("%Y-%m-%d %H:%M:%S").to_string(),
    port
  )
}

#[command]
pub fn log111(message: String) -> String {
  // tauri_plugin_log::logyyy(
  //   tauri_plugin_log::LogLevel::Info,
  //   format!("log111 calling Log-Plugin-Method: {}", message),
  // );

  "".into()
}
